/*
 * globalvar.c
 *
 *  Created on: 2011-11-19
 *      Author: wang
 */

#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <asm/uaccess.h>

MODULE_LICENSE("GPL");

#define MAJOR_NUM 256//major device number,dynamic if 0
int globalvar_major = MAJOR_NUM;

static ssize_t globalvar_read(struct file *,char *,size_t,loff_t *);
static ssize_t globalvar_write(struct file *,const char *,size_t,loff_t *);

struct file_operations globalvar_fops =
{
		read:globalvar_read,
		write:globalvar_write
};
static int globalvar = 0;//the global var we are gonna operate on

static ssize_t globalvar_read(struct file * filp,char * buf,size_t len,loff_t * off)
{
	if(copy_to_user(buf,&globalvar,sizeof(int)))
	{
		return -EFAULT;
	}
	return sizeof(int);
}

static ssize_t globalvar_write(struct file * filp,const char * buf,size_t len,loff_t *off)
{
	if(copy_from_user(&globalvar,buf,sizeof(int)))
	{
		return -EFAULT;
	}
	return sizeof(int);
}

static int  __init globalvar_init(void)
{
	int ret;
	if(!globalvar_major)
	{
		//ret = register();
		;
	}
	else
	{
		ret = register_chrdev(globalvar_major,"globalvar",&globalvar_fops);
	}
	if(ret < 0)
	{
		printk(KERN_WARNING"Globalvar:can't get major %d\n",globalvar_major);
		return ret;
	}
	else
	{
		printk("Globalvar:get major %d\n",globalvar_major);
	}
	return ret;
}

static void __exit globalvar_exit(void)
{
	unregister_chrdev(globalvar_major,"globalvar");//It has no ret value
	printk("Globalvar:unregister!\n");//no fail
}

module_init(globalvar_init);
module_exit(globalvar_exit);
